<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--    卡片-->
    <el-card>
      <!--        搜索-->
      <el-row :gutter="20">

        <el-col :span="10">
          <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>

      </el-row>
      <!--      用户列表-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="" width="180px">
          <template slot-scope="scope">
            <!--            修改用户-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!--            删除用户-->
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="showDeleteDialog(scope.row.id)"></el-button>


            <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
              <el-button @click="showSetRoleDialog(scope.row)" type="warning" icon="el-icon-setting"
                         size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!--    添加用户对话框-->
    <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="handleAddClose"
    >
      <!--     内容主体区域-->
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model.trim="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--    修改用户对话框-->
    <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="handleEditClose"
    >
      <el-form :model="editForm"
               ref="editFormRef"
               :rules="editFormRules"
               label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model.trim="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!--    分配角色对话框-->
    <el-dialog
        title="分配角色"
        :visible.sync="setRolesDialogVisible"
        width="50%"
        @close=""
    >
      <div>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>分配的新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
                v-for="item of roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>


</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (!regEmail.test(value)) {
        return callback(new Error('请输入合法的邮箱'))
      }
      callback()
    }

    var checkPhone = (rule, value, callback) => {
      const regPhone = /1[3456789]\d{9}$/
      if (!regPhone.test(value)) {
        return callback(new Error('请输入合法的手机号'))
      }
      callback()
    }
    return {
      //获取用户列表的参数对象
      queryInfo: {
        // 查询的关键字
        query: '',
        // 每一页显示的条数
        pagesize: 2,
        // 当前页数
        pagenum: 1
      },
      total: 0,
      userList: [],
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 添加表单的数据对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单的数据对象
      editForm: {},
      // 添加用户表单的验证规则对象
      addFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '用户名长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 16, message: '密码长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkPhone, trigger: 'blur'}
        ]
      },
      // 修改用户表单的验证规则
      editFormRules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkPhone, trigger: 'blur'}
        ]
      },
      // 控制分配角色对话框的显示隐藏
      setRolesDialogVisible: false,
      // 用户信息
      userInfo: {},
      // 角色列表
      roleList: [],
      // 已选中的角色ID值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo})
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
      // console.log('xx',this.userList)
      // console.log('ss',res)
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      // console.log('newSize',newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //  监听pagenum改变的事件
    handleCurrentChange(newPage) {
      // console.log('newPage',newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 修改用户状态
    async userStateChange(userinfo) {
      console.log('userinfo', userinfo)
      const {data: res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        // 修改后台数据库的用户状态
        userinfo.mg_state = !userinfo.mg_state
        this.$message.error(res.meta.msg)
        return
      }
      this.$message.success(res.meta.msg)

    },
    // 处理对话框的关闭
    handleAddClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发起添加用户的网络请求
        const {data: res} = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        // 重新获取列表
        this.getUserList()
      })
    },
    // 修改用户(根据id)
    async showEditDialog(id) {
      console.log(id)
      const {data: res} = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改用户表单的重置操作
    handleEditClose() {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        // 关闭修改用户对话框
        this.editDialogVisible = false
        // 重新获取列表
        this.getUserList()
        // 提示用户修改成功
        this.$message.success('修改成功')

      })
    },
    // 删除用户根据id
    async showDeleteDialog(deleteId) {
      console.log('id', deleteId)
      const confirmResult = await this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') return this.$message.info('已取消')
      const {data: res} = await this.$http.delete('users/' + deleteId)
      console.log('res', res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      // 删除成功之后重新发请求
      this.getUserList()


    },
    // 展示分配角色的对话框
    async showSetRoleDialog(userInfo) {
      // console.log('role',userInfo)
      this.userInfo = userInfo
      const {data: res} = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色失败')
      }

      // console.log('res',res)
      this.roleList = res.data
      this.setRolesDialogVisible = true
    },
    // 保存分配的角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }

      // 发送分配角色的请求
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })
      if(res.meta.status !==200){
        return  this.$message.error(res.meta.msg)
      }
      this.$message.success('更新角色成功')
      this.getUserList()
      this.setRolesDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>

</style>
